/**
 * @Name: axios request
 * @Author: tyq
 * @version: 1.0.2
 * @Deprecated: axios 封装
 */
import axios from "axios";
import webConfig from "@/config/config.default";
import _ from 'lodash';
import { ElNotification, ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import { isEmpty, isEmptyObj, isNotEmpty, isNotEmptyObj, formatRequestData } from "./common-api";
import storage from '@/utils/app-storage';
import { tansParams, blobValidate } from '@/utils/ruoyi'
import { saveAs } from 'file-saver'
import cache from '@/plugins/cache'
import errorCode from '@/utils/errorCode'
import useUserStore from '@/store/modules/user'


let downloadLoadingInstance
// 是否显示重新登录
export let isRelogin = { show: false }

// 超时时间 2分钟
axios.defaults.timeout = 120000;
// 默认请求前缀
axios.defaults.baseURL = webConfig.AxiosBaseURL;

// 返回其他状态码
axios.defaults.validateStatus = function (status) {
  // 默认的
  return status >= 200 && status <= 500;
};

// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true;

// http request 拦截
axios.interceptors.request.use(
  (config) => {
    const contentType = config.headers["Content-Type"];
    if (isEmpty(contentType)) config.headers["Content-Type"] = 'application/json; charset=UTF-8';

    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false
    // 是否需要防止数据重复提交
    const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
    if (storage.getToken()) {
      config.headers['Authorization'] = 'Bearer ' + storage.getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
      let url = config.url + '?' + tansParams(config.params)
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }
    if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
      const requestObj = {
        url: config.url,
        data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
        time: new Date().getTime()
      }
      const requestSize = Object.keys(JSON.stringify(requestObj)).length // 请求数据大小
      const limitSize = 5 * 1024 * 1024 // 限制存放数据5M
      if (requestSize >= limitSize) {
        console.warn(`[${config.url}]: ` + '请求数据大小超出允许的5M限制，无法进行防重复提交验证。')
        return config
      }
      const sessionObj = cache.session.getJSON('sessionObj')
      if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
        cache.session.setJSON('sessionObj', requestObj)
      } else {
        const s_url = sessionObj.url                // 请求地址
        const s_data = sessionObj.data              // 请求数据
        const s_time = sessionObj.time              // 请求时间
        const interval = 1000                       // 间隔时间(ms)，小于此时间视为重复提交
        if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
          const message = '数据正在处理，请勿重复提交'
          console.warn(`[${s_url}]: ` + message)
          return Promise.reject(new Error(message))
        } else {
          cache.session.setJSON('sessionObj', requestObj)
        }
      }
    }


    return config;
  },
  (error) => {
    console.log(error)
    Promise.reject(error)
  }
);

// http response 拦截
axios.interceptors.response.use(
  (res) => {

    // 未设置状态码则默认成功状态
    const code = res.status || 200
    // 获取错误信息
    const msg = errorCode[res.status] || res.data.message || errorCode['default']
    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
      return res.data
    }
    if (code === 401) {
      if (!isRelogin.show) {
        isRelogin.show = true
        ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', { confirmButtonText: '重新登录', cancelButtonText: '取消', type: 'warning' }).then(() => {
          isRelogin.show = false
          useUserStore().logOut().then(() => {
            location.href = '/index'
          })
        }).catch(() => {
          isRelogin.show = false
        })
      }
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    } else if (code === 500) {
      ElMessage({ message: msg, type: 'error' })
      return Promise.reject(new Error(msg))
    } else if (code === 601) {
      ElMessage({ message: msg, type: 'warning' })
      return Promise.reject(new Error(msg))
    } else if (code !== 200) {
      ElNotification.error({ title: msg })
      return Promise.reject('error')
    } else {
      return Promise.resolve(res.data)
    }
  },
  (error) => {
    console.log('err' + error)
    let { message } = error
    if (message == "Network Error") {
      message = "后端接口连接异常"
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时"
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常"
    }
    ElMessage({ message: message, type: 'error', duration: 5 * 1000 })
    return Promise.reject(error)
  }
);

/**
 * axios post 请求
 * @param url 请求地址
 * @param data 参数
 * @param headers 请求头
 * @returns {Promise<AxiosResponse<any>>} Promise
 */
export function post(url, data, headers) {
  if (!url) return Promise.reject("post url 不能为空");
  let config = {};
  if (isNotEmpty(headers)) config.headers = headers;
  return axios.post(url, data || {}, config);
}

/**
 * axios get 请求
 * @param url 请求地址
 * @param params 参数
 * @param headers 请求头
 * @returns {Promise<AxiosResponse<any>>} Promise
 */
export function get(url, params = undefined, headers = undefined) {
  if (!url) return Promise.reject("get url 不能为空");
  let config = {};
  if (isNotEmptyObj(params)) config.params = params;
  if (isNotEmptyObj(headers)) config.headers = headers;
  return axios.get(url, config);
}

/**
 * axios get 请求，进行了一次状态处理
 * @param url 请求地址
 * @param params 参数
 * @param headers 请求头
 * @returns {Promise<AxiosResponse<any>>} Promise
 */
export async function doGet(url, params, headers) {
  const res = await get(url, params, headers);
  if (res.status) {
    return res.data;
  } else {
    // 接口请求状态有误，弹窗提示
    ElNotification.error({
      title: '错误',
      message: res.message,
    })
  }
}

// KtlApi 参数组装工具
class PostData {
  constructor() {
    this.data = [];
  }

  dataFormat(value) {
    if (_.isUndefined(value)) {
      return "";
    }

    try {
      return value.toString()
        .replace(/\+/g, "%2b")
        .replace(/=/g, "%3d")
        .replace(/&/g, "%26")
        .replace(/'/g, '$*$*$')
        .replace(/\\/g, '$!$!$')
        .replace(/"/g, '$@$@$')
        .replace(/\n\r/g, "\\n\\r")
        .replace(/\r\n/g, "\\r\\n")
        .replace(/\r/g, "\\r")
        .replace(/\n/g, "\\n");
    } catch (e) {
      console.log("PostData.dataFormat ==> 数据转换失败：");
      console.log(`value=${value.toString()}`);
      console.log("");
      return "";
    }
  }

  add(key, value) {

    let resultData = {};
    try {
      let tmp = '{ "' + key + '": "' + this.dataFormat(value) + '" }';
      resultData = JSON.parse(tmp);
    } catch (e) {
      console.log("PostData.add ==> 字符串转换JSON失败：");
      console.log(`key=${key}, value=${value.toString()}`);
      console.log(e);
      console.log("");
    }

    this.data.push(resultData);
  }

  addItem(item) {
    for (let key in item) {
      //console.log(key + ':' + item[key]);
      item[key] = this.dataFormat(item[key]);
    }

    this.data.push(item);
  }

  toString() {
    try {
      let result = JSON.stringify(this.data);
      result = result.replace(/"/g, "'"); //.replace(/###/g, '"');
      return result;
    } catch (e) {
      console.log("PostData.toString ==> JSON转换字符串失败：");
      console.log(e);
      console.log("");
    }

    return ""
  }
}

export const ApiUrl = {
  Proc: "/DataManager/Proc",
  ProcAddSet: "/DataManager/ProcAddSet",
  ProcSet: "/DataManager/ProcSet"
}

/**
 * axios post 请求，进行了一次状态处理
 * @param params 参数
 * @returns {Promise<AxiosResponse<any>>} Promise
 */
export async function ktlapi(params = undefined) {
  if (isEmptyObj(params)) {
    ElNotification.error({
      title: '错误',
      message: '请求参数有误'
    });

    return Promise.reject('=== ktlapi >>> 错误 422：请求参数有误');
  }

  let defaultConfig = {
    url: '',
    apiurl: ApiUrl.Proc,
    method: 'post',
    name: '',
    data: {},
    headers: {}
  }

  _.assign(defaultConfig, params)
  formatRequestData(defaultConfig.data)

  if (!defaultConfig.url && !defaultConfig.apiurl) {
    ElNotification.error({
      title: '错误',
      message: '请求地址有误'
    });
    return Promise.reject('=== ktlapi >>> 错误 404：请求地址有误');
  }

  if (defaultConfig.method == 'get') {
    try {
      const res = await get(defaultConfig.url, defaultConfig.data, defaultConfig.headers);
      if (res.status) {
        return Promise.resolve(res.data);
      } else {
        // 接口请求状态有误，弹窗提示
        ElNotification.error({
          title: '错误',
          message: res.message,
        })
        return Promise.reject(res.message);
      }
    } catch (err) {
      return Promise.reject(err)
    }
  }

  if (defaultConfig.method == 'post') {
    let requestUrl = defaultConfig.apiurl;
    let requestData = defaultConfig.data;

    if (defaultConfig.url) {
      requestUrl = defaultConfig.url;
    } else {

      const pd = new PostData();
      if (!isEmptyObj(defaultConfig.data)) {
        // 批处理，data应该是数组
        if (defaultConfig.apiurl === ApiUrl.ProcAddSet) {
          // 参数格式校验
          if (!_.isArray(defaultConfig.data)) {
            const errmsg = `${ApiUrl.ProcAddSet}请求的参数应该是数组`;
            ElNotification.error({
              title: '错误',
              message: errmsg,
            })
            return Promise.reject(errmsg);
          }

          defaultConfig.data.forEach(item => {
            pd.addItem(item)
          })
        } else {
          for (let key in defaultConfig.data) {
            pd.add(key, defaultConfig.data[key])
          }
        }
      }

      requestData = {
        Name: defaultConfig.name,
        Parameters: pd.toString()
      }
    }

    try {
      const res = await post(requestUrl, requestData, defaultConfig.headers);
      if (res.status) {
        return Promise.resolve(res.data);
      } else {
        // 接口请求状态有误，弹窗提示
        ElNotification.error({
          title: '错误',
          message: res.message,
        })
        return Promise.reject(res.message);
      }
    } catch (err) {
      return Promise.reject(err)
    }
  }

}

export function download(url, params, filename, config) {
  downloadLoadingInstance = ElLoading.service({ text: "正在下载数据，请稍候", background: "rgba(0, 0, 0, 0.7)", })
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob',
    ...config
  }).then(async (data) => {
    const isBlob = blobValidate(data)
    if (isBlob) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text()
      const rspObj = JSON.parse(resText)
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      ElMessage.error(errMsg)
    }
    downloadLoadingInstance.close()
  }).catch((r) => {
    console.error(r)
    ElMessage.error('下载文件出现错误，请联系管理员！')
    downloadLoadingInstance.close()
  })
}


export default axios;
